use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use eframe::{CreationContext, egui};
use eframe::egui::{Button, Visuals};
use crate::core::common::MyApp;
use crate::core::load_fonts::load_fonts;

#[derive(Default)]
pub struct MainApp {
    is_light: bool,
    show_deferred_viewport: Arc<AtomicBool>,
}


impl MyApp for MainApp {
    fn new(ctx: &CreationContext<'_>) -> Self {
        load_fonts(&ctx.egui_ctx);
        Self::default()
    }
}

impl eframe::App for MainApp {
    fn update(&mut self, ctx: &egui::Context, _: &mut eframe::Frame) {
        egui::CentralPanel::default().show(ctx, |ui| {
            if self.is_light {
                if ui.add(Button::new("☀").frame(false)).on_hover_text("切换到黑暗主题").clicked() {
                    ui.ctx().set_visuals(Visuals::dark());
                    self.is_light = false;
                }
            } else {
                if ui.add(Button::new("☀").frame(false)).on_hover_text("切换到明亮主题").clicked() {
                    ui.ctx().set_visuals(Visuals::light());
                    self.is_light = true;
                }
            }
            ui.heading("嘿嘿嘿");
            let mut show_deferred_viewport = self.show_deferred_viewport.load(Ordering::Relaxed);
            if ui.button("点击开启子窗口").clicked() {
                if !show_deferred_viewport {
                    show_deferred_viewport = true;
                }
            }
            self.show_deferred_viewport.store(show_deferred_viewport, Ordering::Relaxed);
        });
        if self.show_deferred_viewport.load(Ordering::Relaxed) {
            let show_deferred_viewport = self.show_deferred_viewport.clone();
            ctx.show_viewport_deferred(
                egui::ViewportId::from_hash_of("my_child_window1"),
                egui::ViewportBuilder::default().with_title("子窗口").with_inner_size([400.0, 200.0]),
                move |ctx, class| {
                    assert!(class == egui::ViewportClass::Deferred, "当前后端不支持viewports");
                    egui::CentralPanel::default().show(ctx, |ui| {
                        ui.label("这是子窗口的内容");
                    });
                    if ctx.input(|i| i.viewport().close_requested()) {
                        show_deferred_viewport.store(false, Ordering::Relaxed);
                    }
                },
            );
        }
    }
}
